//
//  searchVC.m
//  WuyouTang
//
//  Created by 王敏欣 on 2017/2/17.
//  Copyright © 2017年 cat. All rights reserved.
//

#import "searchVC.h"
#import "HXSearchBar.h"

#import "fansModel.h"
#import "fans.h"
#import "YBCenterVC.h"
#import "SearchHistoryCell.h"
#import "HMSegmentedControl.h"
#import "NearbyVideoModel.h"
#import "VideoCollectionCell.h"
#import "YBGetVideoObj.h"
#import "YBSearchBarView.h"
#import "LiveRankVC.h"
#import "LiveRankCell.h"
#import "YBCheckLiveObj.h"

@interface searchVC ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate,guanzhu,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
//    HXSearchBar *searchBars;
    YBSearchBarView *searchView;
    
    NSInteger _userPaging;
    NSInteger _videoPaging;
    BOOL isHistory;             //是否显示历史
    BOOL isUser;                //是用户还是视频列表
}

@property(nonatomic,strong)UITableView *historyTableView;               //搜索历史
@property(nonatomic,strong)NSMutableArray *historyArray;

@property(nonatomic,strong)UIView *userVideoMix;                        //搜索结果（用户和视频组合）
@property(nonatomic,strong)HMSegmentedControl *segmentedControl;        //segment
@property(nonatomic,strong)UIScrollView *bgScrollView;                  //底部scrollView(承载用户、视频搜索结果界面)

@property (strong, nonatomic)UITableView *userTableView;                //用户搜索
@property(nonatomic,strong)NSArray *userModels;
@property(nonatomic,strong)NSMutableArray *userArray;

@property(nonatomic,strong)UICollectionView *videoCollectinView;        //视频搜索
@property(nonatomic,strong)NSArray *videoModels;
@property(nonatomic,strong)NSMutableArray *videoArray;

@property(nonatomic,strong)UIView *tabHeaderView;
@property(nonatomic,strong)UIView *tabFooterView;
@property(nonatomic,strong)NSArray *weekArr;
@end

@implementation searchVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //[self getUsers];
    //[self getVideoLists];
    //获取搜索历史
    _historyArray = [NSMutableArray arrayWithArray:[common getHistoryArray]];
    [self refreshHistory];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.naviView.hidden = YES;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id) self;
    _userPaging = 1;
    _videoPaging = 1;
//    self.view.backgroundColor = Normal_Color;
    self.view.backgroundColor = RGB(250, 250, 250);
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);

    //历史
    self.historyArray = [NSMutableArray array];
    isHistory = YES;
    
    //用户搜索
    self.userArray = [NSMutableArray array];
    self.userModels = [NSArray array];
    isUser = YES;
    //视频搜索
    self.videoModels = [NSArray array];
    self.videoArray = [NSMutableArray array];
    
    [self addSearchBar];
    [self.view addSubview:self.historyTableView];
    //用户、视频组合
    [self.view addSubview:self.userVideoMix];
    
    self.weekArr = [NSArray array];
    [self getWeekShowLists];
//    [self.view addSubview:self.userTableView];
//    _userTableView.hidden = YES;
//    [self.view addSubview:self.videoCollectinView];
    
}
-(void)getWeekShowLists{
    
    [WYNetworking postWithUrl:@"Home.getWeekShowLists" Dic:nil Suc:^(int code, id info, NSString *msg) {
        _weekArr = info;
        [_historyTableView reloadData];

        } Fail:^(id fail) {
            
        }];
}
#pragma mark - 刷新历史
-(void)refreshHistory {
//    if (_historyArray.count<=0) {
//        [PublicView showTextNoData:_historyTableView text1:@"" text2:YZMsg(@"还没有搜索历史~") centerY:0.8];
//    }else {
//        [PublicView hiddenTextNoData:_historyTableView];
//    }
    [_historyTableView reloadData];
}
#pragma mark - 用户数据
-(NSArray *)userModels{
    NSMutableArray *array = [NSMutableArray array];
    for (NSDictionary *dic in self.userArray) {
        fansModel *model  = [fansModel modelWithDictionary:dic];
        [array addObject:model];
    }
    _userModels = array;
    return _userModels;
}
-(void)getUsers{
    NSString *url = [NSString stringWithFormat:@"Home.search&key=%@&uid=%@&token=%@&p=%ld",searchView.searchTF.text,[Config getOwnID],[Config getOwnToken],(long)_userPaging];

    if (_searchFrom == SearchFrom_City) {
        url = [url stringByAppendingFormat:@"&lng=%@&lat=%@&city=%@",[CityDefault getLocationLng],[CityDefault getLocationLat],_curCity];
    }
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    YBWeakSelf;
    
    [WYNetworking postWithUrl:url Dic:nil Suc:^(int code, id info, NSString *msg) {
        [_userTableView.mj_header endRefreshing];
        [_userTableView.mj_footer endRefreshing];
        if(code == 0) {
            NSArray *infoA = [NSArray arrayWithArray:info];
            if (_userPaging == 1) {
                [_userArray removeAllObjects];
            }
            if (infoA.count <=0) {
                [_userTableView.mj_footer endRefreshingWithNoMoreData];
            }else {
                [_userArray addObjectsFromArray:infoA];
            }
            if (_userArray.count <= 0) {
                [PublicView showTextNoData:_userTableView text1:YZMsg(@"对不起") text2:YZMsg(@"没有搜索到相关内容") centerY:0.8];
            }else{
                [PublicView hiddenTextNoData:_userTableView];
            }
            [_userTableView reloadData];
        }else {
            [PublicView showTextNoData:weakSelf.userTableView text1:YZMsg(@"对不起") text2:YZMsg(@"没有搜索到相关内容") centerY:0.8];
        }
    } Fail:^(id fail) {
        [_userTableView.mj_header endRefreshing];
        [_userTableView.mj_footer endRefreshing];
        [_userArray removeAllObjects];
        [_userTableView reloadData];
        [PublicView showTextNoData:weakSelf.userTableView text1:YZMsg(@"对不起") text2:YZMsg(@"没有搜索到相关内容") centerY:0.8];
    }];

}
#pragma mark - 视频数据
-(NSArray *)videoModels {
    NSMutableArray *m_array = [NSMutableArray array];
    for (NSDictionary *dic in _videoArray) {
        NearbyVideoModel *model = [NearbyVideoModel modelWithDictionary:dic];
        [m_array addObject:model];
    }
    _videoModels = m_array;
    return _videoModels;
}
-(void)getVideoLists {
    NSString *url = [NSString stringWithFormat:@"Home.videoSearch&uid=%@&key=%@&token=%@&p=%ld",[Config getOwnID],searchView.searchTF.text,[Config getOwnToken],(long)_videoPaging];
    if (_searchFrom == SearchFrom_City) {
        url = [url stringByAppendingFormat:@"&lng=%@&lat=%@&city=%@",[CityDefault getLocationLng],[CityDefault getLocationLat],_curCity];
    }
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [WYNetworking postWithUrl:url Dic:nil Suc:^(int code, id info, NSString *msg) {
        [_videoCollectinView.mj_header endRefreshing];
        [_videoCollectinView.mj_footer endRefreshing];
        if (code == 0) {
            NSArray *infoA = [NSArray arrayWithArray:info];
            if (_videoPaging == 1) {
                [_videoArray removeAllObjects];
            }
            if (infoA.count <=0) {
                [_videoCollectinView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [_videoArray addObjectsFromArray:infoA];
            }
            if (_videoArray.count<=0) {
                [PublicView showTextNoData:_videoCollectinView text1:YZMsg(@"对不起") text2:YZMsg(@"没有搜索到相关内容") centerY:0.8];
            }else{
                [PublicView hiddenTextNoData:_videoCollectinView];
            }
            [_videoCollectinView reloadData];
        }else {
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        [_videoCollectinView.mj_header endRefreshing];
        [_videoCollectinView.mj_footer endRefreshing];
        [_videoArray removeAllObjects];
        [_videoCollectinView reloadData];
        [PublicView showTextNoData:_videoCollectinView text1:@"" text2:YZMsg(@"网络错误") centerY:0.8];
    }];
    
    
}

#pragma mark - 清空历史
-(void)clearAllHistory {
    [_historyArray removeAllObjects];
    [common saveHistory:[NSArray arrayWithArray:_historyArray]];
    [self refreshHistory];
}
#pragma mark - 用户列表关注
-(void)doGuanzhu:(NSString *)st{
    [self getUsers];
}
#pragma mark - scrollView 代理
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (scrollView == _bgScrollView) {
        CGFloat pageWidth = scrollView.frame.size.width;
        NSInteger page = scrollView.contentOffset.x / pageWidth;
        [_segmentedControl setSelectedSegmentIndex:page animated:YES];
    }
    
}
//查看更多
-(void)moreLiveRank{
    LiveRankVC *rankVc = [[LiveRankVC alloc]init];
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:rankVc animated:YES];
}

#pragma mark - tableView 代理
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (isHistory) {
        NSLog(@"hhhh----hhhh111");
        if (section == 0) {
            return 50;

        }else{
            return 0;
        }
    }
     NSLog(@"hhhh----hhhh222");
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (isHistory) {
        NSLog(@"hhhh----hhhh111");
        if (section == 0) {
            return 50;

        }else{
            return 0;
        }
    }
     NSLog(@"hhhh----hhhh222");
    return 0;
}

-(UIView *)tabHeaderView {
    if (!_tabHeaderView) {
        _tabHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 50)];
        _tabHeaderView.backgroundColor = UIColor.whiteColor;//CellRow_Cor;
        
        UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 100, 50)];
        title.font = SYS_Font(15);
        title.text = YZMsg(@"搜索历史");
        title.textColor = GrayText;
        [_tabHeaderView addSubview:title];
        UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(15, 49.5, _window_width-30, 0.5)];
        line.backgroundColor = RGB_COLOR(@"#ffffff", 0.06);
        [_tabHeaderView addSubview:line];
        
        UIButton *clearHistory = [UIButton buttonWithType:UIButtonTypeCustom];
        clearHistory.frame = CGRectMake(_window_width-75, 0, 60, 50);
        [clearHistory setTitle:YZMsg(@"清空") forState:0];
        clearHistory.titleLabel.font = SYS_Font(15);
        [clearHistory setTitleColor:GrayText forState:0];
        clearHistory.contentHorizontalAlignment = NSTextAlignmentRight;
        [clearHistory addTarget:self action:@selector(clearAllHistory) forControlEvents:UIControlEventTouchUpInside];
        [_tabHeaderView addSubview:clearHistory];
    }
    return _tabHeaderView;
}

-(UIView *)tabFooterView {
    if (!_tabFooterView) {
        _tabFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 50)];
        _tabFooterView.backgroundColor = UIColor.whiteColor;// RGB_COLOR(@"#09051E", 1);

        UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 100, 50)];
        title.font = SYS_Font(14);
        title.text = YZMsg(@"直播榜单");
        title.textColor = GrayText;
        [_tabFooterView addSubview:title];
        UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(15, 49.5, _window_width-30, 0.5)];
        line.backgroundColor = RGB_COLOR(@"#ffffff", 0.06);
        [_tabFooterView addSubview:line];
        
        UIButton *clearHistory = [UIButton buttonWithType:UIButtonTypeCustom];
        clearHistory.frame = CGRectMake(_window_width-95, 0, 80, 50);
        [clearHistory setTitle:YZMsg(@"查看更多") forState:0];
        clearHistory.titleLabel.font = SYS_Font(14);
        [clearHistory setTitleColor:Pink_Cor forState:0];
        [clearHistory setImage:[UIImage imageNamed:@"shop_right"] forState:0];
        [clearHistory setTitleEdgeInsets:UIEdgeInsetsMake(0, - clearHistory.imageView.image.size.width, 0, clearHistory.imageView.image.size.width)];
        [clearHistory setImageEdgeInsets:UIEdgeInsetsMake(0, clearHistory.titleLabel.bounds.size.width, 0, -clearHistory.titleLabel.bounds.size.width)];

        clearHistory.contentHorizontalAlignment = NSTextAlignmentRight;
        [clearHistory addTarget:self action:@selector(moreLiveRank) forControlEvents:UIControlEventTouchUpInside];
        [_tabFooterView addSubview:clearHistory];
    }
    return _tabFooterView;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (isHistory) {
        NSLog(@"hhhh----vvvvv111==%@",self.tabHeaderView);
        if (section == 0) {
            return self.tabHeaderView;
        }else{
            return nil;
        }
    }
    NSLog(@"hhhh----vvvvv222");
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (isHistory) {
        if (section == 0) {
            return self.tabFooterView;
        }else{
            return nil;
        }

    }
    return nil;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (isHistory) {
        return 2;
    }else{
        return 1;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (isHistory == NO) {
        return self.userModels.count;
    }else{
        //搜索历史
        if (section == 0) {
            return _historyArray.count;
        }else{
            return _weekArr.count;
        }

    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (isHistory == NO) {
        return 90;
    }
    if (indexPath.section == 0) {
        return 50;
    }else{
        return 50;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (isHistory == NO) {
        //用户
        fans *cell = [fans cellForTableView:tableView];
        cell.backgroundColor = UIColor.whiteColor;
        fansModel *model = _userModels[indexPath.row];
        cell.model = model;
        cell.guanzhuDelegate = self;
        if (cell.model.uid ==[Config getOwnID] || [cell.model.uid isEqualToString:[Config getOwnID]])    {
            cell.guanzhubtn.hidden = YES;
        }
        cell.nameL.textColor = UIColor.blackColor;
        cell.lineLb.backgroundColor = RGB(245, 245, 245);
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else {
        if (indexPath.section == 0) {
            //搜索历史
            SearchHistoryCell *cell = [SearchHistoryCell cellWithTab:tableView andIndexPath:indexPath];
            cell.delEvent = ^(NSString *type) {
                if (_historyArray.count >indexPath.row) {
                     [_historyArray removeObjectAtIndex:indexPath.row];
                    [common saveHistory:[NSArray arrayWithArray:_historyArray]];
                    [self refreshHistory];
                }
            };
            cell.contentL.text = _historyArray[indexPath.row];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else{
            LiveRankCell *cell = [LiveRankCell cellWithTab:tableView andIndexPath:indexPath];
            if (indexPath.row < 3) {
                cell.numImg.image = [UIImage imageNamed:[NSString stringWithFormat:@"live_rank%ld",indexPath.row+1]];
                cell.numLb.hidden = YES;
            }else{
                cell.numLb.hidden = NO;
                cell.numLb.text = [NSString stringWithFormat:@"%ld",indexPath.row+1];
            }
            cell.rankData = _weekArr[indexPath.row];
            return cell;
        }
    }
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.view endEditing:YES];
    
    if (isHistory == NO) {
        fansModel *model = _userModels[indexPath.row];
        YBCenterVC *center = [[YBCenterVC alloc]init];
        center.otherUid = model.uid;
        center.isPush = YES;
        //[self.navigationController pushViewController:center animated:YES];
        [[YBBaseAppDelegate sharedAppDelegate] pushViewController:center animated:YES];
    }else {
        if (indexPath.section == 0) {
            searchView.searchTF.text = _historyArray[indexPath.row];
            [self searchBarSearchButtonClicked];
        }else{
            NSDictionary *rankDic = _weekArr[indexPath.row];
            if ([minstr([rankDic valueForKey:@"islive"]) isEqual:@"1"]) {
                [YBCheckLiveObj checkLiveManeger].liveUid = minstr([rankDic valueForKey:@"uid"]);
                [YBCheckLiveObj checkLiveManeger].liveStream = minstr([rankDic valueForKey:@"stream"]);
                [YBCheckLiveObj checkLiveManeger].currentIndex = 0;
                [YBCheckLiveObj checkLiveManeger].listArray = nil;
                [[YBCheckLiveObj checkLiveManeger] checkLiving];

            }else{
                YBCenterVC *center = [[YBCenterVC alloc]init];
                center.otherUid = minstr([rankDic valueForKey:@"uid"]);
                center.isPush = YES;
                //[self.navigationController pushViewController:center animated:YES];
                [[YBBaseAppDelegate sharedAppDelegate] pushViewController:center animated:YES];

            }

        }
    }
    
}
#pragma mark - CollectionView 代理
/*
 * minimumLineSpacing、minimumInteritemSpacing去设置
 -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
 return CGSizeMake(0,0);
 }
 -(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
 {
 return UIEdgeInsetsMake(0,0,0,0);
 }
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 2;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.videoModels.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    VideoCollectionCell *cell = (VideoCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"VideoCollectionCell" forIndexPath:indexPath];
    NearbyVideoModel *model = _videoModels[indexPath.row];
    cell.model = model;
    cell.backgroundColor = CellRow_Cor;
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *vidoeID = minstr([_videoArray[indexPath.row] valueForKey:@"id"]);
    [YBGetVideoObj lookManeger].fromWhere = @"searchVC";
    [YBGetVideoObj lookManeger].videoID = vidoeID;
    [YBGetVideoObj lookManeger].playIndex = (int)indexPath.row;
    [YBGetVideoObj lookManeger].videoList = [_videoArray mutableCopy];
    [YBGetVideoObj lookManeger].paging = (int)_videoPaging;
    NSString *baseUrl = [NSString stringWithFormat:@"Home.videoSearch&key=%@",searchView.searchTF.text];
    [YBGetVideoObj lookManeger].baseUrl = baseUrl;
    [[YBGetVideoObj lookManeger]goLookVC];
    
}

#pragma mark - set/get
//添加搜索条
- (void)addSearchBar {
    UIView *bg = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, statusbarHeight+70)];
    bg.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:bg];
    
    YBWeakSelf;
    searchView = [[YBSearchBarView alloc]initWithFrame:CGRectMake(10,10+statusbarHeight, self.view.frame.size.width -20,60)];
    searchView.searchEvent = ^(RKSearchType searchType) {
        [weakSelf searchEevnt:searchType];
    };
    [bg addSubview:searchView];
    [searchView.searchTF becomeFirstResponder];
    
}

#pragma mark - 搜索事件 s

-(void)searchEevnt:(RKSearchType)searchType {
    if (searchType == RKSearch_Search) {
        //搜索
        [self searchBarSearchButtonClicked];
    }
    if (searchType == RKSearch_Cancle) {
        //取消
        searchView.searchTF.text = @"";
        [searchView.searchTF resignFirstResponder];
        [self.view endEditing:YES];
        [self.navigationController popViewControllerAnimated:YES];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    if (searchType == RKSearch_ValueChange) {
        //输入框改变
        NSString *allText = [searchView.searchTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        if (allText.length > 0) {
            isHistory = NO;
            _historyTableView.hidden = YES;
            _userVideoMix.hidden = NO;
            [_userArray removeAllObjects];
            [_userTableView reloadData];
            
            _userPaging = 1;
            _videoPaging = 1;
            
            [self getUsers];
            [self getVideoLists];
            [self addHistory];
        }else{
            isHistory = YES;
            _userVideoMix.hidden = YES;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                _historyTableView.hidden = NO;
                [self refreshHistory];
            });
        }
    }
    if (searchType == RKSearch_BeginEditing) {
        //开始编辑
        if (searchView.searchTF.text.length>0) {
            isHistory = NO;
            _historyTableView.hidden = YES;
            _userVideoMix.hidden = NO;
        }else{
            isHistory = YES;
            _historyTableView.hidden = NO;
            _userVideoMix.hidden = YES;
        }
    }
    
}

//搜索
- (void)searchBarSearchButtonClicked{
    
    NSString *allText = [searchView.searchTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (allText.length<1) {
        [MBProgressHUD showPop:YZMsg(@"请输入内容")];
        return;
    }
   
    isHistory = NO;
    _historyTableView.hidden = YES;
    _userVideoMix.hidden = NO;
    [self addHistory];
    
    [_userArray removeAllObjects];
    [_userTableView reloadData];
    _userPaging = 1;
    _videoPaging = 1;
    
    [self getUsers];
    
    [self getVideoLists];
    
    [searchView.searchTF resignFirstResponder];
}

-(void)addHistory {
    if (searchView.searchTF.text.length>0) {
        for (NSString *str in _historyArray) {
            if ([str isEqual:searchView.searchTF.text]) {
                [_historyArray removeObject:str];
                break;
            }
        }
        //加入搜索历史
        [_historyArray insertObject:searchView.searchTF.text atIndex:0];
        //最多六条
        if (_historyArray.count>6) {
            [_historyArray removeLastObject];
        }
        [common saveHistory:[NSArray arrayWithArray:_historyArray]];
    }
}

#pragma mark - 搜索事件 end

-(UITableView *)historyTableView {
    if (!_historyTableView) {
        //5个像素间隔
        _historyTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 75+statusbarHeight, _window_width, _window_height-75-statusbarHeight-ShowDiff) style:UITableViewStylePlain];
        _historyTableView.delegate = self;
        _historyTableView.dataSource = self;
        _historyTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _historyTableView.backgroundColor =UIColor.whiteColor;// RGB_COLOR(@"#09051E", 1);//Normal_Color;
    }
    return _historyTableView;
}
-(UIView *)userVideoMix {
    if (!_userVideoMix) {
        CGFloat mixHeight = _window_height-75-statusbarHeight-ShowDiff;
        CGFloat segHeight = 40;
        CGFloat scrollHeight = mixHeight-segHeight;
        //5个像素间隔
        _userVideoMix = [[UIView alloc]initWithFrame:CGRectMake(0, 75+statusbarHeight, _window_width, mixHeight)];
                _segmentedControl = [[HMSegmentedControl alloc] initWithFrame:CGRectMake(0, 0, _window_width, segHeight)];
        NSArray *titleArray = @[YZMsg(@"用户"), YZMsg(@"视频")];
        _segmentedControl.sectionTitles = titleArray;
        _segmentedControl.selectedSegmentIndex = 0;
        _segmentedControl.selectionIndicatorHeight = 2.0;
        _segmentedControl.backgroundColor = UIColor.whiteColor;
        _segmentedControl.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor blackColor]};
        _segmentedControl.selectedTitleTextAttributes = @{NSForegroundColorAttributeName : [UIColor blackColor]};
        _segmentedControl.selectionIndicatorColor = [UIColor blackColor];
        _segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
        _segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        _segmentedControl.tag = 3;
        __weak typeof(self) weakSelf = self;
        [_segmentedControl setIndexChangeBlock:^(NSInteger index) {
            [weakSelf.bgScrollView scrollRectToVisible:CGRectMake(_window_width * index, 0, _window_width, scrollHeight) animated:YES];
        }];
        [_userVideoMix addSubview:_segmentedControl];
        
        _bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, segHeight, _window_width, scrollHeight)];
        _bgScrollView.backgroundColor = UIColor.whiteColor;
        _bgScrollView.pagingEnabled = YES;
        _bgScrollView.showsHorizontalScrollIndicator = NO;
        _bgScrollView.contentSize = CGSizeMake(_window_width *titleArray.count , scrollHeight);
        _bgScrollView.delegate = self;
        [_bgScrollView scrollRectToVisible:CGRectMake(0, 0, _window_width, scrollHeight) animated:NO];
        [_userVideoMix addSubview:_bgScrollView];
        
        //用户
        _userTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, _window_width, scrollHeight) style:UITableViewStylePlain];
        _userTableView.delegate = self;
        _userTableView.dataSource = self;
        _userTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _userTableView.backgroundColor = UIColor.whiteColor;
        _bgScrollView.pagingEnabled = YES;
        _userTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            _userPaging = 1;
            [self getUsers];
        }];
        _userTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            _userPaging += 1;
            [self getUsers];
        }];
        [_bgScrollView addSubview:_userTableView];
        
        //视频
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.itemSize = CGSizeMake(_window_width/2-1, (_window_width/2-1) * 1.4);
        flow.minimumLineSpacing = 2;
        flow.minimumInteritemSpacing = 2;
        _videoCollectinView = [[UICollectionView alloc]initWithFrame:CGRectMake(_window_width, 0, _window_width, scrollHeight) collectionViewLayout:flow];
        [_videoCollectinView registerNib:[UINib nibWithNibName:@"VideoCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"VideoCollectionCell"];
        _videoCollectinView.delegate =self;
        _videoCollectinView.dataSource = self;
        _videoCollectinView.backgroundColor = UIColor.whiteColor;
        _videoCollectinView.mj_footer  = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            _videoPaging ++;
            [self getVideoLists];
        }];
        _videoCollectinView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            _videoPaging = 1;
            [self getVideoLists];
        }];
        [_bgScrollView addSubview:_videoCollectinView];
        
    }
    return _userVideoMix;
}
/*
-(UITableView *)userTableView {
    if (!_userTableView) {
        //5个像素间隔
        _userTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 75+statusbarHeight, _window_width, _window_height-75-statusbarHeight-ShowDiff) style:UITableViewStylePlain];
        _userTableView.delegate = self;
        _userTableView.dataSource = self;
        _userTableView.separatorStyle = UITableViewCellStyleDefault;
        _userTableView.backgroundColor =Normal_Color;
        _userTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            _userPaging = 1;
            [self getUsers];
        }];
        _userTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            _userPaging += 1;
            [self getUsers];
        }];
    }
    return _userTableView;
}

- (UICollectionView *)videoCollectinView {
    if (!_videoCollectinView) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.itemSize = CGSizeMake(_window_width/2-1, (_window_width/2-1) * 1.4);
        flow.minimumLineSpacing = 2;
        flow.minimumInteritemSpacing = 2;
        _videoCollectinView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 75+statusbarHeight, _window_width, _window_height-75-statusbarHeight-ShowDiff) collectionViewLayout:flow];
        [_videoCollectinView registerNib:[UINib nibWithNibName:@"VideoCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"VideoCollectionCell"];
        _videoCollectinView.delegate =self;
        _videoCollectinView.dataSource = self;
        _videoCollectinView.mj_footer  = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            _videoPaging ++;
            [self getVideoLists];
        }];
        _videoCollectinView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            _videoPaging = 1;
            [self getVideoLists];
        }];
    }
    return _videoCollectinView;
}
*/

/*
//加上 搜索栏
searchBars = [[HXSearchBar alloc] initWithFrame:CGRectMake(10,10+statusbarHeight, self.view.frame.size.width -20,60)];
searchBars.backgroundColor = UIColor.redColor;//CellRow_Cor;
searchBars.delegate = self;
//输入框提示
searchBars.placeholder = YZMsg(@"搜索用户|视频");
//光标颜色
searchBars.cursorColor = [UIColor whiteColor];
//TextField
searchBars.searchBarTextField.layer.cornerRadius = 18;
searchBars.searchBarTextField.layer.masksToBounds = YES;
//searchBars.searchBarTextField.layer.borderColor = [UIColor grayColor].CGColor;
//searchBars.searchBarTextField.layer.borderWidth = 1.0;
searchBars.searchBarTextField.backgroundColor = RGB_COLOR(@"#201F37", 1);
searchBars.searchBarTextField.textColor = [UIColor whiteColor];
searchBars.searchBarTextField.font = [UIFont systemFontOfSize:14];
//清除按钮图标
//searchBar.clearButtonImage = [UIImage imageNamed:@"demand_delete"];
UIButton *clearBtn = [searchBars.searchBarTextField valueForKey:@"_clearButton"];
[clearBtn addTarget:self action:@selector(clickClearBtn) forControlEvents:UIControlEventTouchUpInside];
//去掉取消按钮灰色背景
searchBars.hideSearchBarBackgroundImage = YES;
[searchBars becomeFirstResponder];
[bg addSubview:searchBars];
*/
//#pragma mark - 搜索代理
//- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
//    HXSearchBar *sear = (HXSearchBar *)searchBar;
//    sear.cancleButton.backgroundColor = [UIColor clearColor];
//    [sear.cancleButton setTitle:YZMsg(@"取消") forState:UIControlStateNormal];
//    [sear.cancleButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
//    sear.cancleButton.titleLabel.font = [UIFont systemFontOfSize:16];
//
//    if (searchBar.text.length>0) {
//        isHistory = NO;
//        _historyTableView.hidden = YES;
//        _userVideoMix.hidden = NO;
//    }else{
//        isHistory = YES;
//        _historyTableView.hidden = NO;
//        _userVideoMix.hidden = YES;
//    }
//}
////文字改变
//-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
//    if (searchText.length>0) {
//        isHistory = NO;
//        _historyTableView.hidden = YES;
//        _userVideoMix.hidden = NO;
//        [_userArray removeAllObjects];
//        [_userTableView reloadData];
//
//        _userPaging = 1;
//        _videoPaging = 1;
//
//        [self getUsers];
//
//        [self getVideoLists];
//
//    }else{
//        isHistory = YES;
//        _historyTableView.hidden = NO;
//        _userVideoMix.hidden = YES;
//        [self refreshHistory];
//    }
//}
//取消按钮点击的回调
//- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
//    searchBar.showsCancelButton = NO;
//    searchBar.text = nil;
//    [self.view endEditing:YES];
//    [self.navigationController popViewControllerAnimated:YES];
//    [self dismissViewControllerAnimated:YES completion:nil];
//}
//清除按钮
//-(void)clickClearBtn {
//    isHistory = YES;
//    _userVideoMix.hidden = YES;
//    _historyTableView.hidden = NO;
//    [self refreshHistory];
//}

@end
